using Gtk;
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Globalization;
using System.Reflection;

using Serpis;
using PArticulo;


public partial class MainWindow : Gtk.Window
{
	public MainWindow () : base(Gtk.WindowType.Toplevel)
	{
		Build ();
		
		miTreeView.Init(AppDbConnection.Instance.DbConnection, entrySelect.Text);
		
		findAction.Activated += delegate {
			miTreeView.Refresh(entrySelect.Text);
		};
		
		editAction.Activated += delegate {
			
			object id = Convert.ToInt64(miTreeView.GetValue(0));
			
			ArticuloPersister articuloPersister = new ArticuloPersister();
			Articulo articulo = ArticuloPersister.Load(id);
			

			ArticuloView articuloView = new ArticuloView();
			
			Controller controller = new Controller(articulo, articuloView);
			controller.Refresh();
			
			articuloView.SaveAction.Activated += delegate {
				controller.Update();
				
				foreach (PropertyInfo propertyInfo in articulo.GetType().GetProperties())
					Console.WriteLine("{0}={1}", propertyInfo.Name, propertyInfo.GetValue(articulo, null));
				
				articuloView.Destroy();
				
				articuloPersister.Save(articulo);
				
				miTreeView.Refresh();
			};
		};
		
		deleteAction.Activated += delegate {
			MessageDialog messageDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, "¿Esta seguro que desea eliminar el articulo?");
			int response = messageDialog.Run();
			messageDialog.Destroy();
			if(response != (int)ResponseType.Yes)
				return;
			
			object id = Convert.ToInt64(miTreeView.GetValue(0));
			Persister persister = new Persister();
			persister.Delete(id, typeof(Articulo));
			miTreeView.Refresh();
		};
	}
	
	protected void OnDeleteEvent (object sender, DeleteEventArgs a)
	{
		Application.Quit ();
		a.RetVal = true;
	}
}
